package com.kobako.model;

import com.kobako.entity.BbsEntity;
import com.kobako.mybatis.MySFFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by kobako on 2017/4/5.
 * Just a game
 */
@Service("bbsDao")
public class BBSDao {
    public static final int COUNT_PER_PAGE = 5;
    private static final Logger logger = LoggerFactory.getLogger(BBSDao.class);

    public int getPageCount(){
        SqlSession session = getSession();
        int count = -1;
        try{
            String stat = "com.kobako.mybatis.bbsMapper.getCount";
            count = session.selectOne(stat);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
        return count;
    }

    public void save(BbsEntity entity){
        SqlSession session = getSession();
        try{
            String stat = "com.kobako.mybatis.bbsMapper.insertBbs";
            session.insert(stat,entity);
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            session.close();
        }
    }

    private SqlSession getSession(){
        SqlSessionFactory factory = MySFFactory.getSessionFactory();
        if(factory == null){
            logger.warn("Session factory not exist! Get Session error!");
            return null;
        }
        return factory.openSession();
    }

    public List<BbsEntity> getCommentsByPage(int page){
        SqlSession session = getSession();
        if(session == null){
//            logger.error("Get Comments error!Because of the sessionFactory error.");
            return getErrorBbs();
        }
        List<BbsEntity> bbses = null;
        try {
            String stat = "com.kobako.mybatis.bbsMapper.selectByPage";
            HashMap<String ,Integer> map = new HashMap<>();
            map.put("beginNum",getBeginNum(page));
            map.put("returnNum",COUNT_PER_PAGE);
            bbses = session.selectList(stat,map);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Get Comments error!May be the map init error.");
            bbses = getErrorBbs();
        }finally {
            session.close();
        }
        return bbses;
    }

    private List<BbsEntity> getErrorBbs(){
        List<BbsEntity> bbses = new ArrayList<>();
        BbsEntity entity = new BbsEntity();
        entity.setName("ERROR!");
        entity.setComment("如果你看到这条消息表示数据库出现异常，我们正在加紧修复");
        entity.setEmoji("img/emoji/rilegou.jpg");
        bbses.add(entity);
        return bbses;
    }

    private int getBeginNum(int page){
        return (page-1)*COUNT_PER_PAGE;
    }
}
